<template>
  <div>
    <ElText v-show="!writable" truncated class="wfull" @dblclick="onDblClick">{{ value }}</ElText>
    <div v-show="writable">
      <ElAutocomplete v-model="value" :fetch-suggestions="fetchSuggestions" clearable @blur="onBlur" @keyup.enter="onBlur">
        <template #default="{ item }">
          <div class="flex">
            <div>{{ item.label }}</div>
            <div>({{ item.value }})</div>
          </div>
        </template>
      </ElAutocomplete>
    </div>
  </div>
</template>
<script setup lang="ts">
  import { ElText, ElAutocomplete } from 'element-plus';
  import { ref, watch } from 'vue';

  const props = defineProps<{modelValue: any, options: {value: string, label?: string}[]}>()
  const emits = defineEmits(['update:modelValue'])

  const value = ref<string>(props.modelValue)
  const writable = ref(false)

  function fetchSuggestions (keyword: string, cb: any) {
    const results = keyword
      ? props.options.filter(e => e.value.toLowerCase().indexOf(keyword.toLowerCase()) === 0)
      : props.options
    
    cb(results)
  }

  watch(() => props.modelValue, (val) => {
    value.value = val
    if(!value.value) writable.value = true
  }, {immediate: true})

  function onDblClick() {
    writable.value = true
  }

  function onBlur() {
    writable.value = false
    emits('update:modelValue', value.value)
  }
</script>